#ifndef MEMORY_DC_HEADER_H
#define MEMORY_DC_HEADER_H

class CMemDC : public CDC {

public:
// Data members
	HDC m_hDCOriginal;
	RECT m_rcPaint;
	CBitmap m_bmp;
	HBITMAP m_hBmpOld;

// Constructor/destructor
	CMemDC(HWND hWnd, HDC hDC, RECT& rcPaint) : m_hDCOriginal(hDC), m_hBmpOld(NULL)
    {
        m_rcPaint = rcPaint;
        CreateCompatibleDC(m_hDCOriginal);
        ATLASSERT(m_hDC != NULL);
        m_bmp.CreateCompatibleBitmap(m_hDCOriginal, m_rcPaint.right - m_rcPaint.left, m_rcPaint.bottom - m_rcPaint.top);
        ATLASSERT(m_bmp.m_hBitmap != NULL);
        m_hBmpOld = SelectBitmap(m_bmp);
        SetViewportOrg(-m_rcPaint.left, -m_rcPaint.top);

        if (hWnd != NULL) {
            if (GetClassLongPtr(hWnd, GCW_ATOM) == 32770) {
                FillSolidRect(&m_rcPaint, GetSysColor(COLOR_BTNFACE));
            }
            else {
                ULONG_PTR ulpBrush = GetClassLongPtr(hWnd, GCLP_HBRBACKGROUND);
                if (ulpBrush) {
                    FillRect(&m_rcPaint, (HBRUSH)ulpBrush);
                }
                else
                    hWnd = NULL;
            }
        }
        if (hWnd == NULL)
            FillSolidRect(&m_rcPaint, ::GetBkColor(hDC));
    }

	~CMemDC()
	{
		::BitBlt(m_hDCOriginal, m_rcPaint.left, m_rcPaint.top, m_rcPaint.right - m_rcPaint.left, m_rcPaint.bottom - m_rcPaint.top, m_hDC, m_rcPaint.left, m_rcPaint.top, SRCCOPY);
		SelectBitmap(m_hBmpOld);
	}
};

#endif